<template>
	<view class="login-type">
		<view class="logo"><rf-image :preview="false" :src="logo"></rf-image></view>
		<view class="login-container">
			<button class="confirm-btn confirm-btn-bg" :disabled="btnLoading" :class="'text-' + themeColor.name" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">
				微信登录
			</button>
			<!-- <button class="confirm-btn confirm-btn-bg" :disabled="btnLoading" :class="'text-' + themeColor.name" @tap="navTo('/pages/public/login')">已有账号登录</button> -->
			<!-- <button
				class="confirm-btn confirm-btn-bg"
				:disabled="btnLoading"
				:class="'text-' + themeColor.name"
				@tap="navTo(styleLoginType === 'one' ? `/pages/public/register` : `/pages/public/login?type=1`)"
			>
				立即注册
			</button> -->
		</view>
		<!--协议popup-->
		<rf-protocol-popup
			ref="mapState"
			@popupState="popupState"
			protocolPath="/pages/set/about/detail?field=protocol_register&title=注册协议"
			policyPath="/pages/set/about/detail?field=protocol_privacy&title=隐私协议"
			v-if="isRfProtocolPopupShow"
		></rf-protocol-popup>
		<!-- 底部协议 -->
		<view class="footer-protocol" >
			<text @tap="handleRfProtocolPopupShow" class="cuIcon" :class="appAgreementDefaultSelect ? `text-${themeColor.name} cuIcon-radiobox` : 'cuIcon-round'"></text>
			<text class="content">登录表示同意</text>
			<!-- 协议地址 -->
			<text :class="'text-' + themeColor.name" @tap="handleRfProtocolPopupShow">《{{ appName }} 协议》</text>
		</view>
	</view>
</template>
<script>
/**
 * @des 登录类型
 *
 * @author stav stavyan@qq.com
 * @date 2020-01-13 12:02
 * @copyright 2019
 */
import { mpWechatLogin, wechatH5Login, thirdPartyWechatOpenPlatform, thirdPartyApple } from '@/api/login';
import { reqSetWXCode, reqLogin } from '@/api';
import rfProtocolPopup from '@/components/rf-protocol-popup';
export default {
	components: { rfProtocolPopup },
	data() {
		return {
			btnLoading: false,
			isRfProtocolPopupShow: false, // 控制协议popup显示
			appAgreementDefaultSelect: this.$mSettingConfig.appAgreementDefaultSelect, // 是否允许点击登录按钮
			isAuthLoginShow: false,
			isIosAuthLoginShow: false,
			logo: this.$mSettingConfig.appLogo,
			appName: this.$mSettingConfig.appName,
			promoCodeParams: {},
			styleLoginType: this.$mSettingConfig.styleLoginType,
			wechat: this.$mAssetsPath.wechat,
			closeThirdPartyLogin: this.$mSettingConfig.closeThirdPartyLogin,
			loginTypeList: [{ text: '微信', icon: 'iconweixin' }]
		};
	},
	onShow() {
		this.btnLoading = false;
		if (uni.getStorageSync('accessToken')) {
			this.$mRouter.reLaunch({ route: '/pages/index/index' });
		}
		this.getWxCode();
	},
	onLoad(options) {
		this.$mStore.commit('logout');
		/*  #ifdef H5  */
		if (this.$mPayment.isWechat()) {
			this.isAuthLoginShow = true;
		}
		/*  #endif  */
		/*  #ifndef H5 */
		this.isAuthLoginShow = true;
		/*  #endif  */
		/*  #ifdef APP-PLUS */
		if (uni.getSystemInfoSync().platform === 'ios') {
			this.isIosAuthLoginShow = true;
		}
		/*  #endif  */
		// 用户多次点击授权登录会生成多个code 去最后一个code
		this.code = options.code && options.code.split(',')[options.code.split(',').length - 1];
		// 如果不是第一次进来 就不需要强制阅读协议
		if (!uni.getStorageSync('notFirstTimeLogin')) {
			if (!this.appAgreementDefaultSelect) {
				this.appAgreementDefaultSelect = false;
			}
		} else {
			this.appAgreementDefaultSelect = true;
		}
		const backUrl = uni.getStorageSync('backToPage');
		if (backUrl.indexOf('promo_code') !== -1) {
			this.promoCodeParams.promo_code = JSON.parse(backUrl)['query']['promo_code'];
		}
		const _this = this;
		if (this.code) {
			this.btnLoading = true;
			this.$http
				.get(wechatH5Login, {
					code: this.code,
					..._this.promoCodeParams
				})
				.then(async r => {
					this.btnLoading = false;
					if (!r.data.login) {
						this.user_info = r.data.user_info.original;
						uni.showModal({
							content: '您尚未绑定账号，是否跳转登录页面？',
							success: confirmRes => {
								if (confirmRes.confirm) {
									uni.setStorageSync('wechatUserInfo', JSON.stringify(_this.user_info));
									_this.$mRouter.push({ route: '/pages/public/login' });
								} else {
									this.btnLoading = false;
								}
							}
						});
					} else {
						await this.$mStore.commit('login', r.data.user_info);
						const backToPage = uni.getStorageSync('backToPage');
						if (backToPage) {
							if (
								backToPage.indexOf('/pages/profile/profile') !== -1 ||
								backToPage.indexOf('/pages/cart/cart') !== -1 ||
								backToPage.indexOf('/pages/index/index') !== -1 ||
								backToPage.indexOf('/pages/notify/notify') !== -1 ||
								backToPage.indexOf('/pages/category/category') !== -1
							) {
								this.$mRouter.reLaunch(JSON.parse(backToPage));
							} else {
								this.$mRouter.redirectTo(JSON.parse(backToPage));
							}
							uni.removeStorageSync('backToPage');
							uni.removeStorageSync('wechatUserInfo');
						} else {
							this.$mRouter.reLaunch({ route: '/pages/profile/profile' });
						}
					}
				})
				.catch(() => {
					this.btnLoading = false;
				});
		}
	},
	methods: {
		// 通用跳转
		navTo(route) {
			this.$mHelper.toast('暂未开通！');
			return;
			if (!this.appAgreementDefaultSelect) {
				this.$mHelper.toast('请勾选并阅读协议，才能进行下一步哦', 1.5 * 1000);
				return;
			}
			this.$mRouter.redirectTo({ route });
		},
		// 显示协议popup
		handleRfProtocolPopupShow() {
			this.isRfProtocolPopupShow = true;
		},
		// 监听是否同意协议
		popupState(e) {
			if (e) {
				this.appAgreementDefaultSelect = true;
				uni.setStorageSync('notFirstTimeLogin', true);
				this.isRfProtocolPopupShow = false;
			} else {
				this.appAgreementDefaultSelect = false;
				this.isRfProtocolPopupShow = false;
			}
		},

		// 获取微信code
		getWxCode() {
			let that = this;
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					that.wxLogin(loginRes.code);
				},
				fail: err => {
				}
			});
		},

		//将code传给后台
		wxLogin(code) {
			const _this = this;
			_this.$http
				.post(reqSetWXCode, { code })
				.then(response => {
					this.sessionKey = response.session_key;
					this.openid = response.openid;
				})
				.catch(() => {
					// _this.btnLoading = false;
				});
		},

		// 授权登录
		decryptPhoneNumber(e) {
			this.encrypdata = e.detail.encryptedData;
			this.ivdata = e.detail.iv;
			const _this = this;
			_this.$http
				.post(reqLogin, {
					encryptedData: this.encrypdata,
					iv: this.ivdata,
					sessionKey: this.sessionKey,
					openid: this.openid,
					invite_no: 1597076742339
				})
				.then(response => {
					_this.$mStore.commit('login', response);
					_this.$mHelper.toast('登录成功');
					const backToPage = uni.getStorageSync('backToPage');
					if (backToPage) {
						if (
							backToPage.indexOf('/pages/profile/profile') !== -1 ||
							backToPage.indexOf('/pages/cart/cart') !== -1 ||
							backToPage.indexOf('/pages/notify/notify') !== -1 ||
							backToPage.indexOf('/pages/index/index') !== -1 ||
							backToPage.indexOf('/pages/category/category') !== -1
						) {
							_this.$mRouter.reLaunch(JSON.parse(backToPage));
						} else {
							_this.$mRouter.redirectTo(JSON.parse(backToPage));
						}
						uni.removeStorageSync('backToPage');
						uni.removeStorageSync('wechatUserInfo');
					} else {
						_this.$mRouter.reLaunch({
							route: '/pages/profile/profile'
						});
					}
				})
				.catch(() => {
					// _this.btnLoading = false;
				});
		}
	}
};
</script>
<style lang="scss">
page {
	background: #fff;
	height: calc(100% - 88upx);
}

.login-type {
	// padding-top: 180upx;
	height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	.login-container {
		width: 100%;
		flex: .3;
	}
	.logo {
		text-align: center;
		// margin-bottom: 80upx;

		image {
			width: 180upx;
			height: 180upx;
			border-radius: 28upx;
		}
	}
	.confirm-btn {
		width: 70%;
		// margin: 0 7% 50upx;
		height: 84upx;
		line-height: 84upx;
		font-size: $font-lg;
		border: 1upx solid;
	}
	.confirm-btn-bg {
		background: none;
	}
	.footer {
		width: 100%;
		text-align: center;
		position: fixed;
		bottom: 40upx;
		font-size: $font-sm + 2upx;
		.protocol {
			color: $base-color;
			margin: 0 10upx;
		}
	}
}
</style>
